<!DOCTYPE HTML>
<html>

<head>
	<meta charset="utf-8">
	<meta name="renderer" content="webkit|ie-comp|ie-stand">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
	<meta http-equiv="Cache-Control" content="no-siteapp" />
	<!--[if lt IE 9]>
	<script type="text/javascript" src="../../lib/html5shiv.js?rev=@@hash"></script>
	<script type="text/javascript" src="../../lib/respond.min.js?rev=@@hash"></script>
	<![endif]-->
	<!--引入分页-->
	<link rel="stylesheet" href="../../lib/pagination/pagination.css">
	<link rel="stylesheet" type="text/css" href="../../static/h-ui/css/H-ui.min.css" />
	<link rel="stylesheet" type="text/css" href="../../static/h-ui.admin/css/H-ui.admin.css" />
	<link rel="stylesheet" type="text/css" href="../../lib/Hui-iconfont/1.0.8/iconfont.css" />
	<link rel="stylesheet" type="text/css" href="../../static/h-ui.admin/skin/default/skin.css" id="skin" />
	<link rel="stylesheet" type="text/css" href="../../static/h-ui.admin/css/style.css" />
	<link rel="stylesheet" type="text/css" href="../../ht-css/Project.css" />
	<!--表单验证-->
	<link rel="stylesheet" type="text/css" href="../../lib/Validform/5.3.2/style.css" />
	<!--[if IE 6]>
	<script type="text/javascript" src="../../lib/DD_belatedPNG_0.0.8a-min.js" ></script>
	<script>DD_belatedPNG.fix('*');</script>
	<![endif]-->
	<link rel="stylesheet" type="text/css" href="../../ht-css/style-q.css" />
	<link rel="stylesheet" href="../../ht-css/combo.select.css">
	<title>商品管理</title>
	<style>
		.relation {
			background: #FFFFFF;
			border: 1px solid #00a0e9;
		}

		.relation li {
			line-height: 2;
		}

		.relation li:hover {
			background: #00a0e9;
			color: #FFFFFF;
		}

		.guanlian {
			position: absolute;
			top: 35px;
			width: 100%;
			overflow-y: scroll;
			max-height: 150px;
			display: none;
		}

		.guanlian li {
			text-indent: 20px;
		}

		.pagination li {
			float: left;
			margin-left: 5px;
			width: 26px;
			height: 26px;
			border: 1px solid #ccc;
			text-align: center;
			color: #666;
		}

		.pagination li:hover {
			background-color: #5a98de;
		}

		.pagination li:hover a {
			color: #fff;
		}

	</style>
</head>

<body>
<article class="page-container">
	<div class="ml-20 mr-20" id="spuInfo" method="post">
		<div id="tab_topnav" class="HuiTab">
			<div class="tabBar clearfix"><span>图库查找</span><span>本地上传</span></div>
			<div class="tabCon pd-5 bg-1 bk-gray pb-10" style="display: block">
				<div class="lh-30 pd-10">
					<form>
						<table class="table-hover table_li ml-10 mb-10 table">
							<thead class="text-l">
							<tr>
								<td colspan="3" class="col-1-1">
									<div class="row ml-10">
										<label class="form-label f-l pt-5">商品分类：</label>
										<span class="size-M radius col-xs-8 f-l" style="width:15%">
                                     <div style="position: relative;z-index: 900;">
                                          <input type="text" autocomplete="off" class="input-text radius" name="imgClass1" placeholder="请选择一级分类" oninput="imgGoods_listCategory(1)" id="imgClass1" datatype="/^[a-zA-Z0-9\u4e00-\u9fa5]{0,20}$/" errormsg="格式错误，请重新输入" ignore="ignore">
                                          <ul class="relation radius guanlian" id="img-classUl1">

                                          </ul>
                                      </div>
                                      <span class="Validform_checktip"></span>
										</span>
										<span class="f-l pl-10 pr-10 pt-5">~</span>
										<span class="size-M radius col-xs-8 f-l" style="width:15%">
                                      <div style="position: relative;z-index: 900;">
                                          <input type="text" autocomplete="off" class="input-text radius"  name="imgClass2"  placeholder="请选择二级分类" id="imgClass2" datatype="/^[a-zA-Z0-9\u4e00-\u9fa5]{0,20}$/" errormsg="格式错误，请重新输入" ignore="ignore">
                                          <ul class="relation radius guanlian" id="img-classUl2">
                                          </ul>
                                      </div>
                                      <span class="Validform_checktip"></span>
										</span>
										<span class="f-l pl-10 pr-10 pt-5">~</span>
										<span class="size-M radius col-xs-8" style="width:15%">
                                      <div style="position: relative;z-index: 900;">
                                          <input type="text" autocomplete="off" class="input-text radius"  name="imgClass3" placeholder="请选择三级分类" id="imgClass3" datatype="/^[a-zA-Z0-9\u4e00-\u9fa5]{0,20}$/" errormsg="格式错误，请重新输入" ignore="ignore">
                                          <ul class="relation radius guanlian" id="img-classUl3">
                                          </ul>
                                      </div>
                                      <span class="Validform_checktip"></span>
										</span>
									</div>
								</td>
							</tr>
							<tr>
								<td class="col-3-1">
									<div class="row ml-10">
										<label class="form-label f-l pt-5">图片名称：</label>
										<div class="formControls col-xs-8 col-sm-9">
											<input type="text" class="input-text radius" name="imgname" id="imgName" placeholder="输入图片名称关键字" datatype="/^[a-zA-Z0-9\u4e00-\u9fa5]{0,50}$/" errormsg="格式错误，请重新输入" ignore="ignore">
										</div>
										<span class="Validform_checktip"></span>
									</div>
								</td>
								<td class="col-3-1">
									<div class="row ml-10">
										<label class="form-label f-l pt-5">SPU码：</label>
										<div class="formControls col-xs-8 col-sm-9">
											<input type="text" class="input-text radius" name="spuCode" id="spuCode" placeholder="输入SPU码" datatype="n0-11" errormsg="格式错误，请重新输入" ignore="ignore">
										</div>
										<span class="Validform_checktip"></span>
									</div>
								</td>
								<td class="col-3-1">
									<div class="row ml-10">
										<label class="form-label f-l pt-5">CODE码：</label>
										<div class="formControls col-xs-8 col-sm-9">
											<input type="text" class="input-text radius" name="skuCode" id="skuCode" placeholder="输入code码" datatype="n0-11" errormsg="格式错误，请重新输入" ignore="ignore">
										</div>
										<span class="Validform_checktip"></span>
									</div>
								</td>
							</tr>
							</thead>
						</table>
						<div class="text-c mb-10">
							<input id="btn" type="button" class="btn btn-secondary radius size-S botter" onclick="img_list()" value="&nbsp;查&nbsp;&nbsp;询&nbsp;">
							<input name="" type="reset" onclick="resetDiv()" class="btn radius size-S botter ml-10" value="&nbsp;重&nbsp;&nbsp;置&nbsp;">
						</div>
					</form>
					<div class="line"></div>
					<ul id="imgListBox" class="ml-10 sale_pic clearfix">
					</ul>
					<div class="dataTables_wrapper goods_fanye clearfix">
						<div class="f-r pageturning M-box3"></div>
					</div>
					<div class="text-c mb-10">
						<input  type="button" class="btn btn-secondary radius size-S botter" onclick="makeSure()" value="&nbsp;确&nbsp;&nbsp;定&nbsp;">
						<input  type="reset" onclick="cancle()" class="btn radius size-S botter ml-10" value="&nbsp;取&nbsp;&nbsp;消&nbsp;">
					</div>
				</div>
			</div>


			<!--本地上传-->
			<div class="tabCon pd-5 bg-1 bk-gray pb-10" style="display: block">
				<div class="lh-30 pd-10">
					<form>
						<table class="table-hover table_li ml-10 mb-10 table">
							<thead class="text-l">
							<div class="mt-15 mb-30 imgTable clearfix">
								<div class="formControls f-l">
									<span id="imgBox">
									</span>
									<!--<ul class="f-l ml-5 addSpuImgbox">
									</ul>-->
									<input type="button" class="btn btn-secondary radius size-S botter f-l" onclick="addBtn()" value="选择图片">
									<input id="fileUp" type="file" multiple="multiple" onchange="putDataToPage(event)" style="display: none"></div>
							</div>
							</thead>
						</table>
						<div class="text-c mb-10">
							<input type="button" class="btn btn-secondary radius size-S botter" onclick="selectThis(0, 0)" value="&nbsp;确&nbsp;&nbsp;定&nbsp;">
							<input name="" type="reset" onclick="cancle()" class="btn radius size-S botter ml-10" value="&nbsp;取&nbsp;&nbsp;消&nbsp;">
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
	</div>
</article>

<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="../../lib/jquery/1.9.1/jquery.min.js?rev=@@hash"></script>
<script type="text/javascript" src="../../lib/layer/2.4/layer.js?rev=@@hash"></script>
<script type="text/javascript" src="../../static/h-ui/js/H-ui.min.js?rev=@@hash"></script>
<script type="text/javascript" src="../../static/h-ui.admin/js/H-ui.admin.js?rev=@@hash"></script>
<!--/_footer 作为公共模版分离出去-->
<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="../../lib/My97DatePicker/4.8/WdatePicker.js?rev=@@hash"></script>
<!--表单验证-->
<script type="text/javascript" src="../../lib/Validform/5.3.2/Validform_v5.3.2_min.js?rev=@@hash"></script>
<script src="../../lib/pagination/jquery.pagination.js?rev=@@hash"></script>
<script type="text/javascript" src="../../lib/datatables/1.10.0/jquery.dataTables.min.js?rev=@@hash"></script>
<script type="text/javascript" src="../../lib/laypage/1.2/laypage.js?rev=@@hash"></script>
<script type="text/javascript" src="../../ht-js/frame/doT.min.js?rev=@@hash"></script>
<script type="text/javascript" src="../../lib/jquery.combo.select.js?rev=@@hash"></script>
<script src="../../ht-js/public.js?rev=@@hash"></script>
<!--验证token-->
<script src="../../ht-js/verifyToken.js?rev=@@hash"></script>
<script src="../../ht-js/Project.js?rev=@@hash"></script>
<script>
	$(document).ready(function () {
		if (sessionStorage.getItem("isadd") == "false") {
			$("#fileUp").removeAttr("multiple");
		}
	});
    function addBtn() {
		var fileUpEl = document.getElementById('fileUp') ;
		fileUpEl.outerHTML=fileUpEl.outerHTML;
		if(sessionStorage.getItem("isadd") == "true"){
			if($("#imgBox").children().length>=10){
				layer.msg('单次批量上传图片最多10张', {icon: 6,time:1000});
			}else {
				$("#fileUp").trigger('click');
			}
		}else {
			if($("#imgBox").children().length>=1){
				layer.msg('修改图片只能上传一张图片', {icon: 6,time:1000});
			}else {
				$("#fileUp").trigger('click');
			}
		}

    }
    var formData = new FormData();
    var num = 0 ;
    var upFileList = [] ;
    function putDataToPage(e) {
        for (var i = 0; i < e.target.files.length; i++) {
            if (num >=10){return}
            if(i<10&&num+i<10){
				var file = e.target.files.item(i);
				if (!(/^image\/.*$/i.test(file.type))) {
					continue; //不是图片 就跳出这一次循环
				}
				upFileList.push(file) ;
				console.log(file)
				//实例化FileReader API
				var freader = new FileReader();
				freader.readAsDataURL(file);
				freader.onload = function(e) {
					if(num<10){
						$("#imgBox").append('<div class="f-l ml-5 mt-5"><img id="images' + num + '" src="'+ e.target.result + '" style="width:200px;height:200px" class="mr-10"><a onclick="deleteImgFn('+num+',this)" class="text-c" style="display: block;">删除</a></div>') ;
						num++;
					}
				}
			}
        }
    }
    // 失效
    $("#addPicForm").Validform({
        tiptype:2,
        tipSweep:true,
        callback:function(form){
            add_submit();
            return false;
        }
    });
    var btnCount = 0;
    var localStorageParameters = decodeURIComponent(web.readCookie("loginData"));
    var JsonObject =JSON.parse(localStorageParameters);
	//删除图片
	function deleteImgFn(index,el) {
		num--;
		upFileList.splice(index, 1);
		$(el).parent().remove();
	}
    // 失效
    function add_submit() {
        if(btnCount == 0){
            btnCount = 1;
            formData = new FormData();
            formData.append('file', $("#fileUp")[0].files[0]);
            formData.append("oneCategoryId",oneCategoryId);
            formData.append("twoCategoryId",twoCategoryId);
            formData.append("threeCategoryId",threeCategoryId);
            formData.append("creationBy",JsonObject.user.user_ID);
            formData.append("imgName",$("#picName").val());
            $.ajax({
                url: root.goodsInter.goods_saveImg,
                cache: false,  //禁用缓存
                type: "POST",
                // 告诉jQuery不要去处理发送的数据
                processData : false,
                // 告诉jQuery不要去设置Content-Type请求头
                contentType : false,
                data: formData,
                success: function (data) {
                    if(data.errorCode == 0){
                        window.parent.img_list();
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                        showmsg("添加图片成功！",6);
                    }else{
                        //layer.msg(data.errorMessage, {icon: 5,time: 1000});
                        showmsg(data.errorMessage,5);
                        btnCount = 0;
                    }
                }
            });
        }
    }


    function cancle() {
        var ind = parent.layer.getFrameIndex(window.name);
        layer.confirm('确认要取消吗？',function(index){
            parent.layer.close(ind);
            layer.msg('已取消', {icon: 6,time:1000});
        });
    }

    /*tab切换*/
    jQuery.Huitab = function (tabBar, tabCon, class_name, tabEvent, i) {
        var $tab_menu = $(tabBar);
        // 初始化操作
        $tab_menu.removeClass(class_name);
        $(tabBar).eq(i).addClass(class_name);
        $(tabCon).hide();
        $(tabCon).eq(i).show();

        $tab_menu.bind(tabEvent, function () {
            $tab_menu.removeClass(class_name);
            $(this).addClass(class_name);
            var index = $tab_menu.index(this);
            $(tabCon).hide();
            $(tabCon).eq(index).show()
        })
    }
    $(function () {
        $.Huitab("#tab_topnav .tabBar span", "#tab_topnav .tabCon", "current", "click", "0")
    });
    // #tab_demo 父级id
    // #tab_demo .tabBar span 控制条
    // #tab_demo .tabCon 内容区
    // click 事件 点击切换，可以换成mousemove 移动鼠标切换
    // 1	默认第2个tab为当前状态（从0开始）

    /* 本地上传 */
    function selectThis(imgUrl, imgId) {
        if (imgUrl == 0 && imgId == 0) {
            var isSave = sessionStorage.getItem("isSave");// 修改是1 添加是0 -- spu
            formData = new FormData();

            if (upFileList.length == 0) {
                layer.msg("请选择图片！", {icon: 5,time: 2000});
                return false;
            }
            if (isSave == 0) {
                var name = sessionStorage.getItem("name");
                var categoryIds = sessionStorage.getItem("category_ids");
                var splits = categoryIds.split(",");
                for (var i=0;i<upFileList.length;i++){
                    formData.append('file',upFileList[i]);
                }
                formData.append("creationBy",JsonObject.user.user_ID);
                formData.append("imgName",name);
                if (splits[0] != "" && splits[0] != null) {
                    formData.append("oneCategoryId",splits[0]);
                }
                if (splits[1] != "" && splits[1] != null) {
                    formData.append("twoCategoryId",splits[1]);
                }
                if (splits[2] != "" && splits[2] != null) {
                    formData.append("threeCategoryId",splits[2]);
                }
            } else if (isSave == 1) {
            	console.log(upFileList)
                var spuInfo = JSON.parse(sessionStorage.getItem("spuInfo"));
                if(spuInfo.spu.category_id == null){
                    for (var i=0;i<upFileList.length;i++){
                        formData.append('file',upFileList[i]);
                    }
                    formData.append("creationBy",JsonObject.user.user_ID);
                    formData.append("imgName",spuInfo.spu.name);
                }else{
                    var splits = spuInfo.spu.category_ids.split(",");
                    for (var i=0;i<upFileList.length;i++){
                        formData.append('file',upFileList[i]);
                    }
                    formData.append("oneCategoryId",splits[0]);
                    formData.append("twoCategoryId",splits[1]);
                    formData.append("threeCategoryId",splits[2]);
                    formData.append("creationBy",JsonObject.user.user_ID);
                    formData.append("imgName",spuInfo.spu.name);

                }
            }
            if (btnCount == 0) {
                btnCount = 1;
                $.ajax({
                    url: root.goodsInter.goods_saveImages,
                    cache: false,  //禁用缓存
                    type: "POST",
                    // 告诉jQuery不要去处理发送的数据
                    processData : false,
                    // 告诉jQuery不要去设置Content-Type请求头
                    contentType : false,
                    data: formData,
                    async:false,
                    success: function (data) {
                        console.log(data)
                        if(data.errorCode == 0){
//                            var imgSort = sessionStorage.getItem("imgSort");
                            if (data.imgList && data.imgList.length>0){
                                imgHandle(data.imgList,data.imgList.length)
							}
							upFileList = [] ;
                        }else{
                            layer.msg(data.errorMessage, {icon: 5,time: 1000});
                            showmsg(data.errorMessage,5);
                            btnCount = 0;
                        }
                    }
                });
            }
        }
    }

    //由上传一张变更为可上传多张，传入增量图片及长度，追加到已有列表末尾
    function imgHandle(imgList, addSize) {
		if (sessionStorage.getItem("isadd") == "true") {
			if(sessionStorage.getItem("spuImgCache")) {
				var spuImgCache = JSON.parse(sessionStorage.getItem("spuImgCache"));
				var spuInfoImg = JSON.parse(sessionStorage.getItem("spuInfo")).spu_img;
				var canAdd = true;
				for (item in imgList){
					if (spuImgCache.hasOwnProperty(imgList[item].img_id)){
						layer.msg("该图片已存在", {
							icon: 6,
							time: 1000
						});
						canAdd = false;
					}
				}
				if(canAdd == true) {
					var imgLength = sessionStorage.getItem("imgLength");
					var j = 0 ;
					for (var i = Number(imgLength)+1; i <= Number(imgLength) + addSize; i++) {
						var img = "img" + i;
						spuImgCache[img]= {
							imgId: imgList[j].img_id,
							imgUrl: imgList[j].img_url,
							imgSort: i
						}
						j++;
					}
					//调取父级页面属性渲染函数
					window.parent.addSpuPic();
				}
			} else {
				var spuImgCache = {};
				var spuInfoImg = JSON.parse(sessionStorage.getItem("spuInfo")).spu_img;
				var canAdd = true;
				for (item in imgList){
					if (spuInfoImg.hasOwnProperty(imgList[item].img_id)){
						layer.msg("该图片已存在", {
							icon: 6,
							time: 1000
						});
						canAdd = false;
					}
				}
				if(canAdd == true) {
					var imgLength = sessionStorage.getItem("imgLength");
					var j = 0 ;
					for (var i = Number(imgLength)+1; i <= Number(imgLength) + addSize; i++) {
						var img = "img" + i;
						spuImgCache[img]= {
							imgId: imgList[j].img_id,
							imgUrl: imgList[j].img_url,
							imgSort: i
						}
						j++;
					}
				}
			}
		}else {
			var spuImgCache = JSON.parse(sessionStorage.getItem("spuImgCache"));
			var spuImgCacheArr = Object.keys(spuImgCache);
			var imgSort = sessionStorage.getItem("imgSort");
			for (var i = 0; i < spuImgCacheArr.length; i++) {
				var img = "img" + (i + 1);
				if (imgSort == (i + 1)) {
					console.log(img);
					spuImgCache[img] = {
						imgId: imgList[0].img_id,
						imgUrl: imgList[0].img_url,
						imgSort: imgSort
					};
				}
			}
		}

        sessionStorage.setItem("spuImgCache", JSON.stringify(spuImgCache));
		window.parent.imageProcessings();; // 父页面刷新
		var index = parent.layer.getFrameIndex(window.name);
		parent.layer.close(index);
    }

    sessionStorage.removeItem("selectNum");
    /* 图库添加 */
    function makeSure(){//图库添加主图
        var onPicEl = document.getElementsByClassName("onpic");
        var spuImgCache = JSON.parse(sessionStorage.getItem("spuImgCache"));
        var spuImgCacheArr = Object.keys(spuImgCache);

        if (sessionStorage.getItem("isadd") == "true") {
            var imgSort = spuImgCacheArr.length;
            var imgLength = Number(onPicEl.length) + Number(imgSort);

            var imgList = new Array();
            for(var i = 0; i < onPicEl.length; i++){
                imgSort = imgSort + 1;
                var imgObj = {
                    imgId: $(onPicEl[i]).find("#num")[0].innerHTML,
                    imgUrl: $(onPicEl[i]).find("img").attr("src"),
                    imgSort: imgSort
                };
                imgList.push(imgObj);
            }
            for (var i = 0; i < imgLength; i++) {
                for (var j = 0; j < imgList.length; j++) {
                    if (imgList[j].imgSort == (i + 1)) {
                        var img = "img" + (i + 1);
                        spuImgCache[img] = {
                            imgId: imgList[j].imgId,
                            imgUrl: imgList[j].imgUrl,
                            imgSort: imgList[j].imgSort
                        };
                    }
                }
            }
            /*switch(imgSort) {
                case 1:
                    spuImgCache.img1 = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    }
                    break;
                case 2:
                    spuImgCache.img2 = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    }
                    break;
                case 3:
                    spuImgCache.img3 = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    }
                    break;
                case 4:
                    spuImgCache.img4 = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    }
                    break;
                case 5:
                    spuImgCache.img5 = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    }
                    break;
            }*/
        } else {// 图库修改主图
            var imgSort = sessionStorage.getItem("imgSort");
            var imgId = $(onPicEl[0]).find("#num")[0].innerHTML;
            var imgUrl = $(onPicEl[0]).find("img").attr("src");
            for (var i = 0; i < spuImgCacheArr.length; i++) {
                var img = "img" + (i + 1);
                if (imgSort == (i + 1)) {
                    console.log(img);
                    spuImgCache[img] = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    };
                }
            }
            /*switch(imgSort) {
                case '1':
                    spuImgCache.img1 = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    }
                    break;
                case '2':
                    spuImgCache.img2 = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    }
                    break;
                case '3':
                    spuImgCache.img3 = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    }
                    break;
                case '4':
                    spuImgCache.img4 = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    }
                    break;
                case '5':
                    spuImgCache.img5 = {
                        imgId: imgId,
                        imgUrl: imgUrl,
                        imgSort: imgSort
                    }
                    break;
            }*/
        }

        sessionStorage.setItem("spuImgCache", JSON.stringify(spuImgCache));
		window.parent.imageProcessings();; // 父页面刷新
		var index = parent.layer.getFrameIndex(window.name);
		parent.layer.close(index);

    }
    function saveImg(el) {
        var spuImgCache = JSON.parse(sessionStorage.getItem("spuImgCache"));
        if (sessionStorage.getItem("isadd")=="true") {
            var imgLength = sessionStorage.getItem("imgLength");
            if(!$(el).hasClass("onpic")){
                el.classList.add("onpic");
                var num = $(el).find('span')[0];
                var imgId = $(num).html();
                for(item in spuImgCache) {
                    if(spuImgCache[item].imgId == imgId) {
                        $.Huimodalalert('此图片已经存在', 2000);
                        $(el).removeClass("onpic");
                        return false;
                    }
                }
            }else {
                $(el).removeClass("onpic");
            }
        } else {
            var skuImgCache = JSON.parse(sessionStorage.getItem("skuImgCache"));
            if(!$(el).hasClass("onpic")){
                el.classList.add("onpic");
                var num=$(el).find('span')[0];
                var imgId =$(num).html();
                for(item in skuImgCache) {
                    if(skuImgCache[item].imgId == imgId) {
                        $.Huimodalalert('此图片已经存在', 2000);
                        $(el).removeClass("onpic");
                        return false;
                    }
                }
                var onPicEl = document.getElementsByClassName("onpic").length;
                if(1 < onPicEl ){
                    $.Huimodalalert('只能修改一张图片', 2000);
                    $(el).removeClass("onpic");
                    return false;
                }
            }else {
                $(el).removeClass("onpic");
            }
        }


    }

    /**商品图片管理-----------------------------------------------------------------------------------*/
    function imgGoods_listCategory(categoryLevel) {
        var categoryName = $("#imgClass1").val();
        var user_data = {
            categoryLevel: categoryLevel,
            categoryName: $("#imgClass1").val(),
        }
        var succCallBack = function(data, status, response) {
            console.log(data)
            if(data.errorCode == "0") {
                if(data.data == null) {
                    classStr = "<li>无数据</li>"
                    $("#img-classUl1").html(classStr);
                } else {
                    var classStr = "";
                    for(var i = 0; i < data.data.length; i++) {
                        classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                    }
                    $("#img-classUl1").html(classStr);
                }
            }
        }
        web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
    }

    //获取光标
    $("#imgClass1").focus(function() {
        $("#img-classUl1").show();
        imgGoods_listCategory(1, 1);
    });
    $(document).bind("click", function(e) {
        //id为menu的是菜单，id为open的是打开菜单的按钮
        if($(e.target).closest("#img-classUl1").length == 0 && $(e.target).closest("#imgClass1").length == 0) {
            //点击id为menu之外且id不是不是open，则触发
            $("#img-classUl1").hide()
        }
    });

    // 2,3,4级的模糊查询
    function imgGetNext_input(level, category_id) {
        if(level < 4) {
            $("#imgClass" + level + "")[0].oninput = function() {
                console.log(111)
                imgGoods_listCategory(level, level, category_id);
            }
            //获取光标
            $("#imgClass" + level + "").focus(function() {
                $("#img-classUl" + level + "").show();
                imgGoods_listCategory(level, level, category_id);
            });
            $(document).bind("click", function(e) {
                //id为menu的是菜单，id为open的是打开菜单的按钮
                if($(e.target).closest("#img-classUl" + level + "").length == 0 && $(e.target).closest("#imgClass" + level + "").length == 0) {
                    //点击id为menu之外且id不是不是open，则触发
                    $("#img-classUl" + level + "").hide()
                }
            });
        }

    }
    var oneCategoryId = "";
    var twoCategoryId = "";
    var threeCategoryId = "";

    function imgNextClass(category_id, level, category_name) {
        if(level == 1) {
            oneCategoryId = category_id;
        } else if(level == 2) {
            twoCategoryId = category_id;
        } else if(level == 3) {
            threeCategoryId = category_id;
        }
        $("#imgClass" + level + "").val(category_name)
        var user_data = {
            parentCateId: category_id
        }
        var succCallBack = function(data, status, response) {
            console.log(data)
            if(data.errorCode == "0") {
                if(data.data == null) {
                    classStr = "<li>无数据</li>";
                } else {
                    var classStr = "";
                    for(var i = 0; i < data.data.length; i++) {
                        classStr += "<li onclick='imgNextClass(" + data.data[i].category_id + "," + data.data[i].category_level + ",\"" + data.data[i].category_name + "\")'>" + data.data[i].category_name + "</li>"
                    }
                }
                if(data.data[0] == undefined) {
                    classValue = category_id;
                    var nextLevel = level + 1;
                    $("#img-classUl" + nextLevel + "").html(classStr);
                    $("#img-classUl" + level + "").hide();
                } else {
                    var nextLevel = data.data[0].category_level;
                    $("#img-classUl" + nextLevel + "").html(classStr);
                    $("#img-classUl" + nextLevel + "").show();
                    $("#img-classUl" + level + "").hide()
                }
            }
        }
        imgGetNext_input(level + 1, category_id);
        web.doAjax(root.goodsInter.categoryByParam, 'post', user_data, succCallBack);
    }
    $(".classForm").Validform({
        tiptype: 2,
        callback: function(form) {
            console.log(555)
            img_list()
            return false;
        }
    });
    var totalPage = 1;

    function img_list() {

        var categoryName = $("#imgClass3").val();
        var firstCategoryName = $("#imgClass1").val();
        var secondCategoryName = $("#imgClass2").val();
        if (categoryName == "" || categoryName == undefined || categoryName == null) {
            threeCategoryId = -1;
        }

        if (firstCategoryName == "" || firstCategoryName == undefined || firstCategoryName == null) {
            oneCategoryId = -1;
        }

        if (secondCategoryName == "" || secondCategoryName == undefined || secondCategoryName == null) {
            twoCategoryId = -1;
        }

        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: root.goodsInter.goods_listImg,
            cache: false, //禁用缓存
            dataType: "json",
            data: JSON.stringify({
                "pageSize": "10",
                "nowPage": 1,
                "model": {
                    "spuCode": $("#spuCode").val(),
                    "skuCode": $("#skuCode").val(),
                    "imgName": $("#imgName").val(),
                    "oneCategoryId": oneCategoryId,
                    "twoCategoryId": twoCategoryId,
                    "threeCategoryId": threeCategoryId
                }
            }),
            success: function(data) {
                if(data.errorCode == 0) {
                    var imgHtmlStr = "";
                    if(data.data.list != null) {
                        for(var i = 0; i < data.data.list.length; i++) {
                            if (data.data.list[i].img_name == null || data.data.list[i].img_name == "null") {
                                data.data.list[i].img_name = "";
                            }
                            if (data.data.list[i].img_url != null && data.data.list[i].img_url != "null") {
                                imgHtmlStr += '<li onclick="saveImg(this)"><img src="' + data.data.list[i].img_url + '"><div class="num">编码： <span id="num">' + data.data.list[i].img_id + '</span></div><div class="name">名称： <span>' + data.data.list[i].img_name + '</span></div></li>';
                            }
                        }
                        $("#imgListBox").html(imgHtmlStr);
                    }
                    totalPage = data.data.totalPage;
                    $('.M-box3').pagination({
                        pageCount: totalPage,
                        jump: true,
                        coping: true,
                        prevContent: '上页',
                        nextContent: '下页',
                        callback: function(api) {
                            console.log(api.getCurrent());
                            $.ajax({
                                contentType: "application/json",
                                type: "POST",
                                url: root.goodsInter.goods_listImg,
                                cache: false, //禁用缓存
                                dataType: "json",
                                data: JSON.stringify({
                                    "pageSize": "10",
                                    "nowPage": api.getCurrent(),
                                    "model": {
                                        "spuCode": $("#spuCode").val(),
                                        "skuCode": $("#skuCode").val(),
                                        "imgName": $("#imgName").val(),
                                        "oneCategoryId": oneCategoryId,
                                        "twoCategoryId": twoCategoryId,
                                        "threeCategoryId": threeCategoryId
                                    }
                                }),
                                success: function(data) {
                                    console.log(data);
                                    if(data.errorCode == 0) {
                                        var imgHtmlStr = "";
                                        if(data.data.list != null) {
                                            for(var i = 0; i < data.data.list.length; i++) {
                                                if (data.data.list[i].img_name == null || data.data.list[i].img_name == "null") {
                                                    data.data.list[i].img_name = "";
                                                }
                                                if (data.data.list[i].img_url != null && data.data.list[i].img_url != "null") {
                                                    imgHtmlStr += '<li onclick="saveImg(this)"><img src="' + data.data.list[i].img_url + '"><div class="num">编码： <span id="num">' + data.data.list[i].img_id + '</span></div><div class="name">名称： <span>' + data.data.list[i].img_name + '</span></div></li>';
                                                }
                                            }
                                            $("#imgListBox").html(imgHtmlStr);
                                        }
                                        totalPage = data.data.totalPage
                                    }
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown) {
                                    alert(XMLHttpRequest);
                                }
                            });
                        }
                    });
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert(XMLHttpRequest);
            }
        });
    }
</script>
</body>

</html>